import { createSlice, PayloadAction } from '@reduxjs/toolkit';

interface Alert {
  id: string;
  type: 'success' | 'error' | 'info' | 'warning';
  message: string;
}

interface UIState {
  theme: 'light' | 'dark';
  alerts: Alert[];
  sidebarOpen: boolean;
  loading: {
    patterns: boolean;
    challenges: boolean;
    submission: boolean;
    progress: boolean;
  };
}

const initialState: UIState = {
  theme: localStorage.getItem('theme') as 'light' | 'dark' || 'light',
  alerts: [],
  sidebarOpen: false,
  loading: {
    patterns: false,
    challenges: false,
    submission: false,
    progress: false
  }
};

const uiSlice = createSlice({
  name: 'ui',
  initialState,
  reducers: {
    setTheme: (state, action: PayloadAction<'light' | 'dark'>) => {
      state.theme = action.payload;
      localStorage.setItem('theme', action.payload);
    },
    addAlert: (state, action: PayloadAction<Omit<Alert, 'id'>>) => {
      const id = Date.now().toString();
      state.alerts.push({
        id,
        ...action.payload
      });
    },
    removeAlert: (state, action: PayloadAction<string>) => {
      state.alerts = state.alerts.filter(alert => alert.id !== action.payload);
    },
    clearAlerts: (state) => {
      state.alerts = [];
    },
    toggleSidebar: (state) => {
      state.sidebarOpen = !state.sidebarOpen;
    },
    setSidebarOpen: (state, action: PayloadAction<boolean>) => {
      state.sidebarOpen = action.payload;
    },
    setLoading: (state, action: PayloadAction<{ key: keyof UIState['loading']; value: boolean }>) => {
      const { key, value } = action.payload;
      state.loading[key] = value;
    }
  }
});

export const {
  setTheme,
  addAlert,
  removeAlert,
  clearAlerts,
  toggleSidebar,
  setSidebarOpen,
  setLoading
} = uiSlice.actions;

export default uiSlice.reducer; 